using UnityEngine;
using UnityEngine.Events;

[RequireComponent(typeof(Collider))]
public class Button3D : MonoBehaviour
{
    [Header("Button Events")]
    public UnityEvent onClick;  // 对外暴露点击事件

    // 内部事件，不暴露
    private UnityEvent onHoverEnter;
    private UnityEvent onHoverExit;
    private UnityEvent onPress;

    [Header("Manual Settings")]
    [SerializeField]
    private Collider clickCollider;       // 手动拖入 Collider（如果没有，会自动获取自身 Collider）
    [SerializeField, HideInInspector]
    private Renderer targetRenderer;      // 可选颜色反馈
    [SerializeField, HideInInspector]
    private Color normalColor = Color.white;
    [SerializeField, HideInInspector]
    private Color hoverColor = Color.yellow;
    [SerializeField, HideInInspector]
    private Color pressedColor = Color.gray;

    private Color _originalColor;
    private bool hovering = false;

    private void Awake()
    {
         if (clickCollider == null)
        clickCollider = GetComponent<Collider>();

        if (targetRenderer != null)
        {
            _originalColor = targetRenderer.material.color;
        }
        else
        {
            _originalColor = normalColor;
        }
    }

    private void Update()
    {
        if (clickCollider == null) return;

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        // 检测射线击中第一个物体
        if (Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity))
        {
            if (hit.collider == clickCollider)  // 只有射线第一个击中自己的 Collider 才触发
            {
                HandleHover();
                HandlePress();
            }
            else
            {
                HandleExit();
            }
        }
        else
        {
            HandleExit();
        }
    }

    private void HandleHover()
    {
        if (!hovering)
        {
            hovering = true;
            onHoverEnter?.Invoke();
            ChangeColor(hoverColor);
        }
    }

    private void HandlePress()
    {
        if (Input.GetMouseButtonDown(0))
        {
            onPress?.Invoke();
            ChangeColor(pressedColor);
            // Debug.Log("按下了按钮: " + gameObject.name);
        }

        if (Input.GetMouseButtonUp(0))
        {
            onClick?.Invoke();
            ChangeColor(hoverColor);
        }
    }

    private void HandleExit()
    {
        if (hovering)
        {
            hovering = false;
            onHoverExit?.Invoke();
            ChangeColor(normalColor);
        }
    }

    private void ChangeColor(Color color)
    {
        if (targetRenderer != null)
        {
            targetRenderer.material.color = color;
        }
    }

    /// <summary>
    /// 外部调用：临时禁用按钮
    /// </summary>
    public void DisableButton()
    {
        hovering = false;
        ChangeColor(normalColor);
        enabled = false;  // 停止 Update
    }
}
